import path from 'path'
const coneRenderKey = `@conecli${process.platform === 'win32'? '\\':'/'}cone-render`
const coneRenderPath = path.resolve(process.cwd(), './node_modules/@conecli/cone-render')
const coneEditorPath = path.resolve(process.cwd(), './node_modules/@conecli/cone-editor')
const complexFormPath = path.resolve(process.cwd(), './node_modules/@conecli/cone-complex-form')
const watchIgnoredFiles = [path.resolve(process.cwd(), './src/modules/**/*.json')]

const config = {
	projectName: 'cone-module',
	date: '2022-7-1',
	designWidth: 750,
	deviceRatio: {
		640: 2.34 / 2,
		750: 1,
		828: 1.81 / 2,
	},
	compiler: {
		type: 'webpack5',
		prebundle: {
			enable: false
		}
	},
	cache: {
		enable: false // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
	},
	optimization: {
		moduleIds: 'named'
	},
	sourceRoot: 'src',
	outputRoot: `dist/iframe`,
	plugins: [
		['@tarojs/plugin-html', {
			// 装修工具的css不需要做px转rem
			pxtransformBlackList: [/cd-/, /editor-/]
		}]
	],
	defineConstants: {},
	copy: {
		patterns: [
			{ from: path.resolve(process.cwd(), 'libs'), to: path.resolve(process.cwd(), 'dist/iframe/libs') }
		],
		options: {},
	},
	framework: 'react',
	alias: {
		'@src': path.resolve(__dirname, '..', 'src'),
		'@core': path.resolve(process.cwd(), './node_modules/@conecli/cone-editor/dist/core/src'),
		'@editor': path.resolve(process.cwd(), './node_modules/@conecli/cone-editor/dist/editor/src'),
		'@service': path.resolve(process.cwd(), '../../cone-service'),
		'@modules': path.resolve(process.cwd(), 'src/modules'),
	},
	mini: {
		postcss: {
			pxtransform: {
				enable: true,
				config: {},
			},
			url: {
				enable: true,
				config: {
					limit: 1024, // 设定转换尺寸上限
				},
			},
			cssModules: {
				enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
				config: {
					namingPattern: 'module', // 转换模式，取值为 global/module
					generateScopedName: '[name]__[local]___[hash:base64:5]',
				},
			},
		},
		webpackChain(chain, webpack) {
			// chain.merge({
			// 	optimization: {
			// 		minimize: false,
			// 		usedExports: false,
			// 		concatenateModules: false,
			// 	},
			// 	plugin: {
			// 		install: {
			// 			plugin: new webpack.NamedModulesPlugin(),
			// 			args: [],
			// 		},
			// 	},
			// })

			// chain.plugin('ProvidePlugin').use(new webpack.ProvidePlugin({
			// 	//把一个全局变量插入到所有的代码中,支持jQuery plugin的使用;使用ProvidePlugin加载使用频率高的模块
			// 	//provide $, jQuery and window.jQuery to every script
			// 	// $: "jquery",
			// 	// jQuery: "jquery",
			// 	// "window.jQuery": "jquery",
			// 	template: 'art-template/lib/template-web.js'
			//   }), {})

			// 默认taro是不解析node_modules内的多端文件，所以需要在这里主动添加一下针对render包的多端文件解析
			chain.resolve.plugin('MultiPlatformPlugin')
				.tap(args => {
					args[2]["include"] = [coneRenderKey]
					return args
				})

			// 默认不会编译node_modules下的文件，由于render包会包含未编译的文件类型，所以这里需要主动添加一下
			chain.module
				.rule('shop-react-open-compile-babel')
				.test(/\.[tj]sx?$/i)
				.use('babel')
				.loader('babel-loader')
				.options({ presets: ['@babel/preset-react'] })

			chain.module
				.rule('shop-react-open-compile-babel')
				.include.add(coneRenderPath)

			chain.module
				.rule('shop-react-open-compile-scss')
				.test(/\.scss$/)
				.oneOf('normal')
				.use('sass')
				.loader('sass-loader')

			chain.module
				.rule('shop-react-open-compile-scss')
				.include.add(coneRenderPath)

			// 解决node_module下render包的px不会被转成rpx的问题。以下内容来自于 @tarojs/webpack-runner/dist/util/chain.js，只是为了重写postcss规则的exclude部分。tarojs默认把所有node_modules都给排除掉了
			const excludeSet = chain.module.rule('postcss').exclude.store
			excludeSet.clear()
			excludeSet.add(filename => {
				const isNodeModule = (filename) => /\bnode_modules\b/.test(filename);
				const taroModuleRegs = [/@tarojs[/\\_]components/, /\btaro-components\b/];
				const defaultEsnextModuleRegs = [
					/@tarojs[/\\_]components/,
					/\btaro-components\b/,
					/@tarojs[/\\_]taro-h5/,
					/\btaro-h5\b/,
					/@tarojs[/\\_]router/,
					/\btaro-router\b/,
					/@tarojs[/\\_]redux-h5/,
					/\btaro-redux-h5\b/,
					/@tarojs[/\\_]mobx-h5/,
					/\btaro-mobx-h5\b/
				];
				const getEsnextModuleRules = esnextModules => {
					return [...defaultEsnextModuleRegs, ...esnextModules];
				};
				const esnextModuleRules = getEsnextModuleRules([]);
				const isTaroModule = (filename) => taroModuleRegs.some(reg => reg.test(filename));
				const isEsnextModule = (filename) => esnextModuleRules.some(pattern => {
					if (pattern instanceof RegExp) {
						return pattern.test(filename);
					}
					else {
						return filename.indexOf(pattern) > -1;
					}
				});
				if (isTaroModule(filename)) {
					return true;
				}
				else if (isEsnextModule(filename)) {
					return false;
				}
				else {
					return isNodeModule(filename) && !filename.includes(coneRenderKey);
				}
			})
		},
	},
	h5: {
		publicPath: '//isvdev.jd.com/iframe/',
		router: {
			// mode: 'browser'
		},
		output: {
			filename: 'js/[name].js',
			chunkFilename: 'js/[name].js',
			chunkLoadingGlobal: `jshopTaroWebpackJsonp`, // 用于异步加载chunk，与shop-react工程中打包一致
		},
		staticDirectory: 'static',
		enableExtract: false, // extract 开关，开启后将使用 mini-css-extract-plugin 分离 css 文件
		postcss: {
			autoprefixer: {
				enable: true,
				config: {},
			},
			cssModules: {
				enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
				config: {
					namingPattern: 'module', // 转换模式，取值为 global/module
					generateScopedName: '[name]__[local]___[hash:base64:5]',
				},
			},
		},
		webpackChain(chain, webpack) {
			chain.merge({
				optimization: {
					minimize: false,
					usedExports: false,
					runtimeChunk: false,
					concatenateModules: false,
				},
				// plugin: {
				// 	install: {
				// 		plugin: new webpack.NamedModulesPlugin(),
				// 		args: [],
				// 	},
				// },
			})

			chain.plugin('ProvidePlugin').use(new webpack.ProvidePlugin({
				//把一个全局变量插入到所有的代码中,支持jQuery plugin的使用;使用ProvidePlugin加载使用频率高的模块
				//provide $, jQuery and window.jQuery to every script
				// $: "jquery",
				// jQuery: "jquery",
				// "window.jQuery": "jquery",
				template: 'art-template/lib/template-web.js'
			}), [])

			// 默认taro是不解析node_modules内的多端文件，所以需要在这里主动添加一下针对render包的多端文件解析
			chain.resolve.plugin('MultiPlatformPlugin')
				.tap(args => {
					args[2]["include"] = [coneRenderKey]
					return args
				})

			// fixed compile error: Can't import the named export XXXX from non EcmaScript module (only default export is available)
			chain.module
				.rule('mjs$')
				.test(/\.mjs$/)
				.include
				.add(/node_modules/)
				.end()
				.type('javascript/auto');

			// 默认不会编译node_modules下的文件，由于render包会包含未编译的文件类型，所以这里需要主动添加一下
			chain.module
				.rule('shop-react-open-compile-babel')
				.test(/\.[tj]sx?$/i)
				.use('babel')
				.loader('babel-loader')
				.options({ presets: ['@babel/preset-react'] })

			chain.module
				.rule('shop-react-open-compile-babel')
				.include.add(coneRenderPath)

			chain.module
				.rule('shop-react-open-compile-babel')
				.include.add(coneEditorPath)

			chain.module
				.rule('shop-react-open-compile-babel')
				.include.add(complexFormPath)

			chain.module
				.rule('shop-react-open-compile-scss')
				.test(/\.scss$/)
				.oneOf('normal')
				.use('sass')
				.loader('sass-loader')

			chain.module
				.rule('shop-react-open-compile-scss')
				.include.add(coneRenderPath)

			chain.module
				.rule('shop-react-open-compile-scss')
				.include.add(coneEditorPath)

			chain.module
				.rule('shop-react-open-compile-scss')
				.include.add(complexFormPath)

			chain.module
				.rule('art-template-loader')
				.test(/\.(tpl|art)$/)
				.use('art-template-loader')
				.loader('art-template-loader')

			// 解决node_module下render包的px不会被转成rem的问题。以下内容来自于 @tarojs/webpack-runner/dist/util/chain.js，只是为了重写postcss规则的exclude部分。tarojs默认把所有node_modules都给排除掉了
			const excludeSet = chain.module.rule('postcss').exclude.store
			excludeSet.clear()
			excludeSet.add(filename => {
				const isNodeModule = (filename) => /\bnode_modules\b/.test(filename);
				const taroModuleRegs = [/@tarojs[/\\_]components/, /\btaro-components\b/];
				const defaultEsnextModuleRegs = [
					/@tarojs[/\\_]components/,
					/\btaro-components\b/,
					/@tarojs[/\\_]taro-h5/,
					/\btaro-h5\b/,
					/@tarojs[/\\_]router/,
					/\btaro-router\b/,
					/@tarojs[/\\_]redux-h5/,
					/\btaro-redux-h5\b/,
					/@tarojs[/\\_]mobx-h5/,
					/\btaro-mobx-h5\b/
				];
				const getEsnextModuleRules = esnextModules => {
					return [...defaultEsnextModuleRegs, ...esnextModules];
				};
				const esnextModuleRules = getEsnextModuleRules([]);
				const isTaroModule = (filename) => taroModuleRegs.some(reg => reg.test(filename));
				const isEsnextModule = (filename) => esnextModuleRules.some(pattern => {
					if (pattern instanceof RegExp) {
						return pattern.test(filename);
					}
					else {
						return filename.indexOf(pattern) > -1;
					}
				});
				if (isTaroModule(filename)) {
					return true;
				}
				else if (isEsnextModule(filename)) {
					return false;
				}
				else {
					return isNodeModule(filename) && !filename.includes(coneRenderKey);
				}
			})

		},
		devServer: {
			port: 8885,
			host: '127.0.0.1',
			open: false, // 是否在server启动后自动打开页面
			watchFiles: {
				options: {
					ignored: watchIgnoredFiles,
				},
			},
			client: {
				progress: true,
				logging: "warn",
				overlay: {
					errors:true,
					warnings: false
				}
			},
			webSocketServer: false,
			hot: 'only',
			allowedHosts: 'all',
			historyApiFallback: true,
		},
	},
}

module.exports = function (merge) {
	if (process.env.NODE_ENV === 'development') {
		return merge({}, config, require('./dev'))
	}
	return merge({}, config, require('./prod'))
}
